import { Button, Checkbox, Select } from 'antd'
import CommonModal from './CommonEditModal.tsx'
import { DeleteFilled } from '@ant-design/icons'
import { forwardRef, memo, useEffect, useState } from 'react'
import { localShoppingData, tempData } from '@/views/ShoppingCart/LocalShoppingData.ts'
import { getMapList } from '@/api/shoppingCart.ts'
import { message } from '@hs-admin/utils/StaticMethod.ts'
import { commonSelectProps } from '@/views/ShoppingCart/commonProps.ts'

const EditIndustryScope = forwardRef((props: { itemId: string; done: (() => void) | undefined; disabled?: boolean }, ref) => {
  const notEditable = !!props.disabled

  const haveCommon = !!localShoppingData('common')

  const [isChoosing, setIsChoosing] = useState(false)
  const [mapOptions, setMapOptions] = useState([])

  const [mapValue, setMapValue] = useState<null | {
    label: string
    value: string
  }>(null)
  const [mapList, setMapList] = useState<
    Array<{
      name: string
      id: string
    }>
  >([])

  const [useParent, setUseParent] = useState(false)

  const searchMap = (word?: string) => {
    getMapList({
      keyword: word
    }).then((res) => {
      setMapOptions(
        (res.items ?? []).map((item) => ({
          label: item.name,
          value: item.map_id
        }))
      )
    })
  }

  useEffect(() => {
    let data = tempData('mapList') ?? []
    if (props.itemId === 'common') {
      data = localShoppingData(props.itemId, 'mapList') ?? []
      setUseParent(false)
    } else {
      const useP1 = tempData('p1') ?? false
      setUseParent(useP1)
    }
    setMapList(data)
  }, [props.itemId])

  return (
    <CommonModal
      ref={ref}
      title="产业范围选择"
      onOk={() => {
        if (notEditable) return
        props.done?.()
        if (props.itemId === 'common') {
          localShoppingData(props.itemId, { mapList })
        } else {
          tempData({ mapList })
          tempData({
            p1: useParent
          })
        }
      }}
      onCancel={() => {
        console.log('取消')
      }}>
      <div className="flex flex-col gap-6 px-9">
        {props.itemId !== 'common' && haveCommon && (
          <div>
            <Checkbox
              checked={useParent}
              onChange={(e) => {
                setUseParent(e.target.checked)
                if (e.target.checked) {
                  setMapList([])
                }
              }}>
              使用整体范围
            </Checkbox>
          </div>
        )}
        {!useParent && (
          <>
            {mapList.map((item, index) => (
              <div key={item.id}>
                <div className="flex gap-1">
                  <span className="flex-1">{item.name}</span>
                  {!notEditable && (
                    <DeleteFilled
                      onClick={() => {
                        setMapList((prevState) => prevState.toSpliced(index, 1))
                      }}
                    />
                  )}
                </div>
              </div>
            ))}
            {isChoosing ? (
              <div className="flex gap-4">
                <Select
                  {...commonSelectProps}
                  showSearch
                  onSearch={searchMap}
                  onFocus={() => {
                    searchMap()
                  }}
                  value={mapValue?.value}
                  onChange={(_, option) => {
                    setMapValue(option)
                  }}
                  filterOption={false}
                  className="flex-1"
                  options={mapOptions}></Select>
                <Button
                  type="primary"
                  onClick={() => {
                    if (mapValue) {
                      if (mapList.some((item) => item.id === mapValue.value)) {
                        message.error('已存在')
                        return
                      }
                      setMapList((prevState) => [
                        ...prevState,
                        {
                          name: mapValue?.label,
                          id: mapValue?.value
                        }
                      ])
                      setMapValue(null)
                      setIsChoosing(false)
                    }
                  }}>
                  确定
                </Button>
                <Button
                  onClick={() => {
                    setIsChoosing(false)
                  }}>
                  取消
                </Button>
              </div>
            ) : (
              !notEditable && (
                <Button type={'primary'} onClick={() => setIsChoosing(true)}>
                  + 添加图谱
                </Button>
              )
            )}
          </>
        )}
      </div>
    </CommonModal>
  )
})

export default memo(EditIndustryScope)
